/**
 * 记录妆容数据 用于卸载  和 购买提示等
 */

import { MCommonTipPage } from "../../common/MCommonTipPage";
import { GameEventCenter } from "../../GameEventCenter";
import { FuncItemInfo, GlobalObj, LableCfg } from "../../obj/GlobalObj";
import { PGCServer } from "../../PGCServer";
import { GoodsType, LevelData } from "../../uiComp/LevelListComp";
import { DressUpDataParse } from "../DressUpDataParse";
import { MDressUp } from "../MDressUp";
import { DressUpData } from "./DressUpData";
import { DressUpServerDataMgr } from "./DressUpServerDataMgr";


export class DressUpNoteMgr {

    /** 妆容 map 用于记录当前装扮的部位和对应的id数据，在退出装扮时会根据是否购买删除未购买的数据 */
    _dressUpMap: Map<DressUpPart, number[]> = new Map();
    readonly dressUpKey: string = "customData";

    ownDressUpDatas: Map<string, DressUpData> = new Map();//拥有的装扮
    noOwnDressUpDatas: Map<string, DressUpData> = new Map();// 未拥有的装扮

    public tempData: any;// 公用变量数据
    public cacheLoadDressDatas:any[];

    public add(data: DressUpData, levelData: LevelData<FuncItemInfo>) {
        if (!data) return;
        let key = this._getKey(levelData);
        if (!key) return;

        let canUse = DressUpServerDataMgr.Ins.canUse(data, levelData, data);
        let type: DressUpOwnTypeEnum = canUse ? DressUpOwnTypeEnum.OWN : DressUpOwnTypeEnum.NO_OWN;

        console.log("添加装扮数据 :" + key + ", " + type + "," + data.preform_name);
        switch (type) {
            case DressUpOwnTypeEnum.OWN:


                this.ownDressUpDatas.set(key, data);
                this.noOwnDressUpDatas.delete(key);
                break;
            case DressUpOwnTypeEnum.NO_OWN:

                this.noOwnDressUpDatas.set(key, data);
                break;

            default:
                break;
        }
    }

    private _getKey(levelData: LevelData<FuncItemInfo>): string {
        if (!levelData) return;
        let preData = levelData;
        let key: string = "";
        while (preData.preNode) {
            if (preData.preNode.type == GoodsType.ZHUANG_RONG) {
                key = preData.type;
                break;
            }
            preData = preData.preNode;
        }
        if (!key) {
            console.error("没有找到对应的key", levelData)
            return;
        }

        key = preData.type + "," + preData.preNode.type;
        return key;
    }

    public del(levelData: LevelData<FuncItemInfo>) {
        let key = this._getKey(levelData);
        if (key) {
            this.noOwnDressUpDatas.delete(key);
            this.ownDressUpDatas.delete(key);
            console.log("清除部位数据:--->" + key);
        }
    }


    public addByPart(part:DressUpPart, ids:number[]){
        if(ids && ids.length >= 1){

            let levelType = this.getLevelTypeByPart(part);
            let levelData = MDressUp.Ins.findLevelData(levelType);
            let dressData = DressUpServerDataMgr.Ins.getDressUpDataById(ids[0]);
            this.cacheLoadDressDatas ||= [];
            if(dressData){
                this.cacheLoadDressDatas.push(dressData);// 添加到缓存数组中 后面一起加载
            }
            this.add(dressData, levelData);
        }else{
            let levelType = this.getLevelTypeByPart(part);
            console.warn("没有妆容部件id：" + levelType);
        }
    }

    /** 开始加载预制里面的json数据 */
    public loadCacheDressDatas(){
        if(this.cacheLoadDressDatas && this.cacheLoadDressDatas.length){
            DressUpDataParse.loadArrJson(this.cacheLoadDressDatas, Laya.Handler.create(this, ()=>{
                console.log("load 缓存的妆容数据成功");
            }));
            this.cacheLoadDressDatas.length = 0;
        }
    }
    

    public needBuyDressUp(): boolean {
        return this.noOwnDressUpDatas.size > 0;
    }

    public getNoOwnPrice():number{
        this.tempData = 0;
        this.noOwnDressUpDatas.forEach(item => { this.tempData += (item.preform_price || 0) });
        return this.tempData;
    }

    public buyNoOwnDress(callback: Laya.Handler) {

        this.tempData = 0;
        this.noOwnDressUpDatas.forEach(item => { this.tempData += (item.preform_price || 0) });
        let price: number = this.tempData;
        if (GlobalObj.useData.crystal >= price) {
            this.openConfirmBuy(price, callback);
        } else {
            //TODO 购买
            MCommonTipPage.openAlert([
                {
                    top: 90,
                    centerX: 0,
                    labelCfgs: new LableCfg(price + "水晶购买未拥有妆容", 24, "#000000")
                },
                {
                    top: 130,
                    centerX: 0,
                    labelCfgs: new LableCfg("水晶不足", 24, "#000000")
                }
            ], callback);
        }
    }

    private openConfirmBuy(price: number, callback: Laya.Handler) {
        if (this.needBuyDressUp()) {
            //TODO 购买
            MCommonTipPage.openSp([
                {
                    top: 90,
                    labelCfgs: new LableCfg("是否使用" + price + "的水晶值购买", 24, "#000000", 380, true)
                },
                {
                    top: 130,
                    labelCfgs: new LableCfg("未拥有的妆容产品", 24, "#000000", 380, true)
                }
            ], null, Laya.Handler.create(this, this.buyGoods, [callback]));
            // MCommonTipPage.open("是否使用"+data.preform_price+"的水晶值购买"+data.preform_name+"（产品 ）", null, Laya.Handler.create(this, this.onConfirmShop, [selectItem,callback]));
        } else {
            callback.run();
        }
    }

    private buySingleGoods(callback: Laya.Handler) {
        this.tempData = this.noOwnDressUpDatas.size;

        function __checkOver(c: Laya.Handler, count: number) {
            console.log("  ————note checkCount----------------->" + count);
            if (count <= 0) {

                GameEventCenter.Ins.event(GameEventCenter.UPDATE_CRYSTAL);
                MDressUp.Ins.recoverNoOwnDress();
                c && c.run();
            }
        }

        let dressIds: any[] = [];
        this.noOwnDressUpDatas.forEach((item: DressUpData, key: string) => {
            let arr = key.split("_");
            PGCServer.ins.buyGoods(item.preform_id, Laya.Handler.create(this, (data: any) => {
                this.tempData--;
                if (data && data.ret == 0) {
                    MDressUp.Ins.buyDressReport(arr[0], item.preform_name);
                    this.noOwnDressUpDatas.delete(key);
                    this.ownDressUpDatas.set(key, item);
                } else {
                    console.log("购买失败妆容id:" + key, item.preform_id);
                }
                __checkOver(callback, this.tempData);
            }), Laya.Handler.create(this, () => {
                this.tempData--;
                console.log("购买失败妆容id:" + key, item.preform_id);
                __checkOver(callback, this.tempData);
            }));
        })
    }

    private buyGoods(callback: Laya.Handler) {
        this.tempData = this.noOwnDressUpDatas.size;

        function __checkOver(c: Laya.Handler, count: number) {
            console.log("  ————note checkCount----------------->" + count);
            if (count <= 0) {

                GameEventCenter.Ins.event(GameEventCenter.UPDATE_CRYSTAL);
                MDressUp.Ins.recoverNoOwnDress();
                c && c.run();
            }
        }

        let dressIds: any[] = [];
        this.noOwnDressUpDatas.forEach((item: DressUpData, key: string) => {
            dressIds.push(item.preform_id);

        });
        PGCServer.ins.buyGoodsMulti(dressIds, Laya.Handler.create(this, (data: any) => {
            debugger
            if (data && data.ret == 0) {
                let arr = data.data;
                if (arr && arr.length) {
                    for (let index = 0; index < arr.length; index++) {
                        const id = arr[index];
                        this.setOwnDress(id);
                    }
                }
                // this.noOwnDressUpDatas.delete(key);
                // this.ownDressUpDatas.set(key, item);
            } else {
                console.log("购买失败妆容id:", dressIds);
            }
            __checkOver(callback, 0);
        }), Laya.Handler.create(this, () => {
            // GameTool.tips("购买失败!");
            // callback && callback.run();
            __checkOver(callback, 0);
        }))
    }

    setOwnDress(preform_id: number) {
        this.noOwnDressUpDatas.forEach((item: DressUpData, key: string) => {
            if (item && item.preform_id == preform_id) {
                console.log("购买了已经在未购买列表的妆容数据:" + item.preform_name + " id:" + item.preform_id);
                let reportKey = DressUpServerDataMgr.Ins.gettagMap(item);
                MDressUp.Ins.buyDressReport(reportKey, item.preform_desc);

                this.ownDressUpDatas.set(key, item);
                this.noOwnDressUpDatas.delete(key);
            }
        })
    }

    /** 保存新手引导的 */
    public saveNewPlayer() {
        let arr: number[] = [];
        this.ownDressUpDatas.forEach(item => {
            arr.push(item.goods_define_id);
        });
        if (arr.length) {
            PGCServer.ins.newUserFreeBuyGoods(arr, Laya.Handler.create(this, (data: any) => {
                if (data && !data.ret) {
                    console.log("购买免费妆容成功!!!");
                }
            }));
        } else {
            console.warn("未选择开放妆容");
        }
    }

    /**
     * 获取选中的id号数组
     * @param levelData 当前选中的层级标签
     * @returns 
     */
    public getSelectIdxArr(levelData:LevelData<FuncItemInfo>):number[]{
        if(levelData){

            let type = levelData.type;
            let preType = levelData.preNode.type;
            let partType = this.getPartByLevelType(type, preType);
            let partData = this._dressUpMap.get(partType);
            if(partData){
                return partData;
            }
        }
        return [];
    }


    public getPartByLevelType(type: GoodsType, pretype: GoodsType): DressUpPart {
        let partType: DressUpPart;
        if (type == GoodsType.Z_SAI_HONG) {
            partType = DressUpPart.Z_SAI_HONG;
        } else if (type == GoodsType.Z_KOU_HONG || pretype == GoodsType.Z_KOU_HONG) {
            partType = DressUpPart.Z_KOU_HONG;
        } else if (type == GoodsType.Z_DING_ZHUANG) {
            partType = DressUpPart.Z_DING_ZHUANG;
        } else if ([type, pretype].indexOf(GoodsType.Z_YAN_YING) >= 0) {
            partType = DressUpPart.Z_YAN_YING;
        } else if (type == GoodsType.Z_JIE_MAO) {
            partType = DressUpPart.Z_JIE_MAO;
        } else if (type == GoodsType.Z_MEI_MAO) {
            partType = DressUpPart.Z_MEI_MAO;
        } else if (type == GoodsType.Z_YAN_XIAN) {
            partType = DressUpPart.Z_YAN_XIAN;
        } else if (type == GoodsType.Z_FEN_DI_YE || pretype == GoodsType.Z_FEN_DI_YE) {
            partType = DressUpPart.Z_FEN_DI_YE;
        } else if (type == GoodsType.Z_XIU_RONG) {
            partType = DressUpPart.Z_XIU_RONG;
        }
        return partType;
    }

    public getLevelTypeByPart(partType: DressUpPart): GoodsType {
        let type:GoodsType;
        switch (partType) {
            case DressUpPart.Z_SAI_HONG:
                type = GoodsType.Z_SAI_HONG;
                break;
            case DressUpPart.Z_KOU_HONG:
                type = GoodsType.Z_KOU_HONG;
                break;
            case DressUpPart.Z_DING_ZHUANG:
                type = GoodsType.Z_DING_ZHUANG;
                break;
            case DressUpPart.Z_YAN_YING:
                type = GoodsType.Z_YAN_YING;
                break;
            case DressUpPart.Z_JIE_MAO:
                type = GoodsType.Z_JIE_MAO;
                break;
            case DressUpPart.Z_MEI_MAO:
                type = GoodsType.Z_MEI_MAO;
                break;
            case DressUpPart.Z_YAN_XIAN:
                type = GoodsType.Z_YAN_XIAN;
                break;
            case DressUpPart.Z_FEN_DI_YE:
                type = GoodsType.Z_FEN_DI_YE;
                break;
            case DressUpPart.Z_XIU_RONG:
                type = GoodsType.Z_XIU_RONG;
                break;
        }
        return type;
    }



    /**
     * 更新dressMap数据 
     * @param key 妆容部位
     * @param value 妆容部位id
     * @param idx 0:表示颜色类型的更新 或者没有画法类型的妆容  1：画法数据  不填则直接覆盖数据
     * @returns 
     */
    public updateDressUpMap(key: DressUpPart | any, value: number | any, idx?: number): void {
        if (key > 100 || (!key && key !== 0)) return console.error("错误的part key:" + key);
        let dressPartArr = this._dressUpMap.get(key);
        if (typeof idx == "number") {
            if (dressPartArr) {
                dressPartArr[idx] = value;
            } else {
                dressPartArr = [];
                dressPartArr[idx] = value;
                this._dressUpMap.set(key, dressPartArr);
            }
        } else {
            if (value) {
                this._dressUpMap.set(key, value);
            } else {
                this._dressUpMap.delete(key);
            }
            console.log("覆盖数据:key -->" + key + " value-->", value);
        }
        console.log("刷新 dressUpMap:", this._dressUpMap);
    }



    public clearDressMap() {
        this._dressUpMap.clear();
    }


    public getDressUpHeadData(headBoneData: any): any {
        let obj: any = {};
        this._dressUpMap.forEach((value: number[], key: DressUpPart, map: Map<DressUpPart, number[]>) => {
            obj[key] = value;
        });

        headBoneData[this.dressUpKey] = obj;
        return headBoneData;
    }



    public clear() {
        this.cacheLoadDressDatas = null;
        this.clearDressMap();
        this.ownDressUpDatas.clear();
        this.noOwnDressUpDatas.clear();
    }
}

export enum DressUpOwnTypeEnum {
    NO_OWN,
    OWN
}

/** 妆容数据 */
export enum DressUpPart {
    // --------------- 妆容界面
    /** 粉底液 */
    Z_FEN_DI_YE,//"粉底液";
    /** 修容 */
    Z_XIU_RONG,//"修容";
    /** 定妆 */
    Z_DING_ZHUANG,//"大白饼";
    /** 腮红 */
    Z_SAI_HONG,//"腮红";
    /** 眉毛 */
    Z_MEI_MAO,//"眉笔";
    /** 眼线 */
    Z_YAN_XIAN,//"眼线";
    /** 睫毛 */
    Z_JIE_MAO,//"妆容_睫毛";
    /** 眼影 */
    Z_YAN_YING,//"眼影";
    /** 口红 */
    Z_KOU_HONG,//"口红";
}